package com.person.android.ui.activity;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.baidu.mobstat.StatService;
import com.person.android.dao.FileInfo;
import com.person.android.domain.FileListBaseAdapter;
import com.person.android.domain.FileSearchTask;
import com.person.android.domain.FileSearchTask.OnNotifyActivityUpdateListener;
import com.person.android.formatts.R;
import com.person.android.utils.FileSearchType;
import com.person.android.utils.MessageSendUtils;
import com.person.android.utils.ToastUtils;
import com.person.android.widgets.FileSelectAlertDialog;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Stack;

/**
 * @autor zhaokang.
 * @time on 2015/12/10.
 */
public class FileListActivity extends Activity implements View.OnClickListener, OnNotifyActivityUpdateListener {

    private final static String TAG = "FileListActivity";
    private static final String mRootPath = "/mnt/sdcard";  //根路径

    private ImageButton mBackIBV;                           //返回按钮
    private TextView mCurrentTvPath;                        //当前的路径
    private RelativeLayout mBackContainer;                  //返回按钮容器
    private ListView mFileListView;                         //文件选择列表
    private ProgressDialog mTraverseDialog;                 //遍历文件的加载圈
    private FileListBaseAdapter mListAdapter;               //文件列表的适配器
    private Context mContext = FileListActivity.this;

    private List<FileInfo> mFileInfoList;                   //文件的信息列表

    private Stack<String> mPathStack = new Stack<>();       //路径保存列表
    private boolean mIsFirstIn = false;

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case FileSearchType.TRAVERSE_SUCCESS:
                    onPostRunnableExecute();
                    break;
                case FileSearchType.TRAVERSE_EXCEPTION:
                    onPostRunnableExecuteException();
                    break;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_file_list);

        findViews();
        setListeners();
        initialUIWithFileList();
        setListViewOnItemListener();
    }

    private void setListViewOnItemListener() {
        ListViewItemClickListener itemListener = new ListViewItemClickListener();
        mFileListView.setOnItemClickListener(itemListener);
    }

    private void onPostRunnableExecute() {
        ToastUtils.dismissProgressDialog(mTraverseDialog);
        if (mIsFirstIn) {
            mListAdapter = new FileListBaseAdapter(FileListActivity.this, mFileInfoList);
            mFileListView.setAdapter(mListAdapter);
            mIsFirstIn = false;
        } else {
            mListAdapter.notifyDataSetChanged();
        }
    }

    private void onPostRunnableExecuteException() {
        ToastUtils.dismissProgressDialog(mTraverseDialog);
    }

    @Override
    public void onNotifyActivityUpdate(List<FileInfo> fileInfoList, int type) {
        if (mFileInfoList != null) {
            mFileInfoList.clear();
        }
        for (FileInfo info : fileInfoList) {
            FileInfo temp = new FileInfo();
            temp.filePath = info.filePath;
            temp.type = info.type;
            temp.fileNum = info.fileNum;
            temp.lastModifiedInfo = info.lastModifiedInfo;
            this.mFileInfoList.add(temp);
        }
        MessageSendUtils.sendMessage(mHandler, type);
    }

    private String mLastPath;

    private final class ListViewItemClickListener implements AdapterView.OnItemClickListener {
        boolean dismiss = false;

        @Override
        public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
            mPathStack.push(mLastPath);
            final String path = mFileInfoList.get(i).filePath;
            mCurrentTvPath.setText(path);
            File file = new File(path);
            if (file.isDirectory()) {
                refreshListView(i);
                mLastPath = path;
            } else {
                //弹出对话框
                FileSelectAlertDialog.Builder dialog = new FileSelectAlertDialog.Builder(mContext);

                dialog.setTitle(R.string.file_select_title_hint);
                dialog.setMessage(R.string.select_this_audio_file);

                dialog.setPositiveButton(R.string.select_audio_file_ok, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        Intent intent = new Intent();
                        Bundle data = new Bundle();
                        data.putString("path", path);
                        intent.putExtras(data);
                        setResult(0, intent);
                        dismiss = true;
                        dialogInterface.dismiss();
                        finish();
                    }
                });

                dialog.setNegativeButton(R.string.select_audio_file_no, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        dialogInterface.dismiss();
                    }
                });
                if (!dismiss) {
                    dialog.create().show();
                }
            }
        }
    }

    //更新UI，即更新ListView的显示内容
    private void refreshListView(int i) {
        mTraverseDialog = ToastUtils.showProgressDialog(this, getString(R.string.traversing_files), mTraverseDialog);
        String path = mFileInfoList.get(i).filePath;
        new FileSearchTask(path).setOnFileSearchListener(this).start();
    }

    //初始化界面
    private void initialUIWithFileList() {
//        mPathStack.push(mRootPath);
        mLastPath = mRootPath;
        mFileInfoList = new ArrayList<>();
        mCurrentTvPath.setText(mRootPath);
        mTraverseDialog = ToastUtils.showProgressDialog(this, getString(R.string.traversing_files), mTraverseDialog);
        new FileSearchTask(mRootPath).setOnFileSearchListener(this).start();
    }

    private void setListeners() {
        mBackIBV.setOnClickListener(this);
        mBackContainer.setOnClickListener(this);
    }

    private void findViews() {
        mIsFirstIn = true;
        mBackIBV = (ImageButton) findViewById(R.id.ibv_back);
        mCurrentTvPath = (TextView) findViewById(R.id.tvPath);
        mFileListView = (ListView) findViewById(R.id.file_list);
        mBackContainer = (RelativeLayout) findViewById(R.id.ibv_back_container);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.ibv_back:
            case R.id.ibv_back_container:
                backClickAction();
                break;
        }
    }

    private void backClickAction() {
        if ((mPathStack != null) && (mPathStack.size() > 0)) {
            mTraverseDialog = ToastUtils.showProgressDialog(this, getString(R.string.traversing_files), mTraverseDialog);
            String path = mPathStack.pop();
            mCurrentTvPath.setText(path);
            new FileSearchTask(path).setOnFileSearchListener(this).start();
        } else {
            finish();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        StatService.onResume(this);
    }

    @Override
    protected void onPause() {
        super.onPause();
        StatService.onPause(this);
    }
}
